import datetime
import os

from django.http import HttpResponseNotFound
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
# 蜘蛛库，如果存在则判定是蜘蛛
from web.settings import BASE_DIR

MOBILE_USERAGENTS = ("Sogou web spider",'Sogou inst spider',"Sogou Spider","Sogou","spider","Sosospider","bingbot","Yahoo","sogou","bot","Baiduspider","360Spider","speedy_spider","search","xfruits","Google","Monitor")
class Row1(MiddlewareMixin):


    def process_request(self,request):
        def writetxt(usermsg,user):
            # print(request.META)
            if user == 'zhizhu':
                try:
                    with open(os.path.join(BASE_DIR, 'static\\zhizhulog.txt'), 'a+', encoding='utf-8') as f:
                        f.write('[时间]' + datetime.datetime.now().strftime('%m-%d %H:%M:%S') + usermsg+'\n')
                except:
                    pass
            else:
                try:
                    with open(os.path.join(BASE_DIR, 'static\\yonghu.txt'), 'a+', encoding='utf-8') as f:
                        f.write('[时间]' + datetime.datetime.now().strftime('%m-%d %H:%M:%S') + usermsg+'\n')
                except:
                    pass

        # print("中间件1请求   "+request.META["HTTP_USER_AGENT"])
        if any(ua for ua in MOBILE_USERAGENTS if ua in request.META["HTTP_USER_AGENT"]):
            print("蜘蛛")
            writetxt("蜘蛛"+request.META["HTTP_USER_AGENT"],"zhizhu")
            # return HttpResponseNotFound(content="<h1>Not Found</h1><p>The requested URL "+request.path_info+" was not found on this server.</p>")
        else:
            # print("普通用户")
            writetxt("用户"+request.META["HTTP_USER_AGENT"],'')
        return None
    def process_response(self,request,response):
        # print("中间件1返回")
        return response

